const tree = function tree(data, pid = '0', result = []) {
  data.forEach((e) => {
    const el = e;
    el.children = el.children || [];
    if (el.pid === pid) {
      result.push(el);
      const { _id: id } = el;
      tree(data, id, el.children);
    }
  });
  return result;
};

module.exports = {
  /**
   * 大纲排序
   */
  async outlineSort(req) {
    await req.outlinesModel.outlineSort(req.params);
    return {};
  },
  /**
   * 获取大纲
  */
  async getOutlines(req) {
    const result = await req.outlinesModel.getOutlines(req.query);
    return tree(JSON.parse(JSON.stringify(result)));
  },
  /**
   * 添加
  */
  async addOutline(req, { boom }) {
    const {
      outlinename,
    } = req.payload;
    const outlinenameExist = await req.outlinesModel.isExist('outlinename', outlinename);
    if (outlinenameExist) {
      return boom.badRequest('大纲已存在');
    }
    const result = await req.outlinesModel.addOutlines(req.payload);
    return result;
  },

  /**
   * 根据ID获取单个大纲信息
   */
  async getOutlineById(req) {
    const result = await req.outlinesModel.getOutlineById(req.params.id);
    return result;
  },

  /**
   * 根据ID删除大纲
   */
  async deleteOutlineById(req, { boom }) {
    const { _id: pid } = await req.outlinesModel.getOutlineById(req.params.id);
    const nodes = await req.outlinesModel.getChildrenNodes(pid);
    if (nodes.length) {
      return boom.badRequest('请先删除子节点');
    }
    await req.outlinesModel.deleteOutlineById(req.params.id);

    return {};
  },

  /**
   * 根据ID更新大纲信息
  */
  async updateOutlineById(req, { boom }) {
    const {
      outlinename,
    } = req.payload;

    const outline = await req.outlinesModel.getOutlineById(req.params.id);
    if (outline.outlinename !== outlinename) {
      const outlinenameExist = await req.outlinesModel.isExist('outlinename', outlinename);
      if (outlinenameExist) {
        return boom.badRequest('大纲已存在');
      }
    }
    await req.outlinesModel.updateOutlineById(req.params.id, req.payload);
    return {};
  },

  /**
   * 判断字段值是否存在
  */
  async isExist(req) {
    const { field, value } = req.query;
    const result = await req.outlinesModel.isExist(field, value);
    return Boolean(result);
  },
};
